package com.vishop.controllers;

import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import com.vishop.models.Merk;
import com.vishop.services.MerkService;
import com.vishop.services.ProductService;

@Controller
public class MerkController
{
	@Autowired
	private MerkService merkService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private MerkFormValidator validator;
	
	
	@RequestMapping("/alleMerken")
	public ModelAndView getAllMerks()
	{
		ModelAndView mav = new ModelAndView("showMerken");
		Collection<Merk> merken = merkService.getAll();
		mav.addObject("alleMerken", merken);
		return mav;
	}
	
	@RequestMapping(value="/saveMerk", method=RequestMethod.GET)
	public ModelAndView newuserForm()
	{
		ModelAndView mav = new ModelAndView("newMerk");
		Merk merk = new Merk();
		mav.getModelMap().put("newMerk", merk);
		return mav;
	}
	
	@RequestMapping(value="/saveMerk", method=RequestMethod.POST)
	public String create(@ModelAttribute("newMerk")Merk merk, BindingResult result, SessionStatus status)
	{
		validator.validate(merk, result);
		if (result.hasErrors()) 
		{				
			return "newMerk";
		}
		merkService.save(merk);
		status.setComplete();
		return "redirect:alleMerken.htm";
	}
	
	@RequestMapping(value="/updateMerk", method=RequestMethod.GET)
	public ModelAndView edit(@RequestParam("id")Integer id)
	{
		ModelAndView mav = new ModelAndView("editMerk");
		Merk merk = merkService.getById(id);
		mav.addObject("editMerk", merk);
		return mav;
	}
	
	@RequestMapping(value="/updateMerk", method=RequestMethod.POST)
	public String update(@ModelAttribute("editMerk") Merk merk, BindingResult result, SessionStatus status)
	{
		validator.validate(merk, result);
		if (result.hasErrors()) {
			return "editMerk";
		}
		merkService.update(merk);
		status.setComplete();
		return "redirect:alleMerken.htm";
	}
	
	@RequestMapping("deleteMerk")
	public ModelAndView delete(@RequestParam("id")Integer id)
	{
		ModelAndView mav = new ModelAndView("redirect:alleMerken.htm");
		Collection merken = productService.getProductByMerk(id);

		if(merken.isEmpty()){
			merkService.delete(id);
		}
		return mav;
	}	
}
